package com.xhwl.centiotdata.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloud.apigateway.sdk.utils.Client;
import com.cloud.apigateway.sdk.utils.Request;
import com.xhwl.centiotdata.handler.eesd.impl.EesdHuaWeiBaHandler;
import com.xhwl.centiotdata.mq.producer.GeneralProducer;
import com.xhwl.centiotdata.pojo.dto.eesd.EesdConfigDTO;
import com.xhwl.centiotdata.pojo.dto.ganwei.GanweiRomaDeviceDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.enums.eesd.EesdMethodEnum;
import com.xhwl.centiotdata.pojo.enums.pedestrian.PedestrianMethodEnum;
import com.xhwl.centiotdata.pollingtrigger.eesd.EesdDispatcher;
import com.xhwl.centiotdata.pollingtrigger.env.LanJuDispatcher;
import com.xhwl.centiotdata.pollingtrigger.info.InfoDispatcher;
import com.xhwl.centiotdata.pollingtrigger.pedestrian.PedestrianDispatcher;
import com.xhwl.centiotdata.pollingtrigger.roma.RomaDeviceDispatcher;
import com.xhwl.centiotdata.pollingtrigger.visitor.VisitorDispatcher;
import com.xhwl.centiotdata.service.integrateconfig.EESDIntegrationConfig;
import com.xhwl.centiotdata.service.integrateconfig.IntegrationConfig;
import com.xhwl.centiotdata.service.integrateconfig.PedestrianIntegrationConfig;
import com.xhwl.centiotdata.suppliersystem.eesd.batown.BaAccessUtil;
import com.xhwl.centiotdata.suppliersystem.eesd.batown.BaApiHandler;
import com.xhwl.centiotdata.suppliersystem.eesd.hwweather.HwWeatherHandler;
import com.xhwl.centiotdata.suppliersystem.eesd.lanju.LanjuApiHandler;
import com.xhwl.centiotdata.suppliersystem.eesd.wmzz.EesdWmzzApiHandler;
import com.xhwl.centiotdata.suppliersystem.ganwei.GanweiIoTHandler;
import com.xhwl.centiotdata.suppliersystem.haikangyunmou.HaiKangYunMouUtils;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.bi.DwdFactEnvironmentMetrics;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.utils.StatisticsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.groovy.util.Maps;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 18:46 2021/1/14
 */
@RestController
@Slf4j
public class IndexController {
    @Autowired
    GeneralProducer generalProducer;
    @Autowired
    private BaApiHandler baApiHandler;

    @Autowired
    private EESDIntegrationConfig eesdIntegrationConfig;
    @Autowired
    private PedestrianDispatcher pedestrianDispatcher;
    @Autowired
    private InfoDispatcher infoDispatcher;
    @Autowired
    private EesdWmzzApiHandler eesdWmzzApiHandler;
    @Autowired
    private HwWeatherHandler hwWeatherHandler;

    @Autowired
    private LanjuApiHandler lanjuApiHandler;

    @Autowired
    private EesdDispatcher eesdDispatcher;

    @Autowired
    private LanJuDispatcher lanJuDispatcher;

    @Autowired
    private PedestrianIntegrationConfig integrationConfig;

    @Autowired
    EesdHuaWeiBaHandler eesdHuaWeiBaHandler;

    @Autowired
    GanweiIoTHandler ganweiIoTHandler;
    @Autowired
    RomaDeviceDispatcher romaDeviceDispatcher;
    @Autowired
    VisitorDispatcher visitorDispatcher;
    @Autowired
    private HaiKangYunMouUtils haiKangYunMouUtils;
    /**
     * 清除设备缓存
     */
    @RequestMapping(value = "/weather/device/clear")
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void weatherClear() {
        EesdHuaWeiBaHandler.deviceMap.clear();
        EesdHuaWeiBaHandler.treeMap.clear();
    }

    /**
     * 路址查询
     */
    @RequestMapping(value = "/org/index")
    public ResultJson orgQuery(String orgId, Integer projectId) {
        DeviceDTO dto = new DeviceDTO();
        DwdFactEnvironmentMetrics baseInfo0 = eesdHuaWeiBaHandler.getBaseInfo(projectId, orgId, dto, LocalDateTime.now());
        return ResultJson.success(Maps.of("id", baseInfo0.getFloorId(), "pid", baseInfo0.getRoomId()));
    }

    /**
     * 能耗的直接对接
     */
    @RequestMapping(value = "/wmzz/index")
    public Object wmzzindex(int type) {
        EesdConfigDTO eesdConfigDTO = eesdIntegrationConfig.getIntegrationConfig(EesdMethodEnum.WMZZ.getId()).get(0);
        if (type == 0) {
            String result = HttpUtil.get(eesdConfigDTO.getElectricHost());
            return JSON.parseArray(result, Map.class);
        }
        eesdConfigDTO.setIsType(type);
        return eesdWmzzApiHandler.pullRecord(eesdConfigDTO);
    }

    /**
     * 奥莱BA
     */
    @RequestMapping(value = "/ba/index")
    public Object baIndex(int type) {
        switch (type) {
            case 1:
                BaAccessUtil baAccessUtil = new BaAccessUtil("http://172.50.73.250/OpenApi/Http/", "60b65d85c2724796b8da2b0dcb130417", "63b8cb5cf1784e448ad7be3a930ca6bd","afd2fad8f8fc458686bfb51d4c9baf15");
                return baAccessUtil.<Map<String, Object>>getSiteTree();
            case 2:
                eesdDispatcher.executeBaAlarm();
                return null;
        }

        return null;
    }

    /**
     * 奥莱BA详情
     */
    @RequestMapping(value = "/ba/detail")
    public Object badetail(int type,
                           @RequestParam(value = "id", required = false, defaultValue = "dad0d328008449c384fe5040d9e0511b") String id) {
        EesdConfigDTO eesdConfigDTO = eesdIntegrationConfig.getIntegrationConfig(6).get(0);
        if (type == 1) {
            BaAccessUtil baAccessUtil = new BaAccessUtil("http://172.50.73.250/OpenApi/Http/", "60b65d85c2724796b8da2b0dcb130417", "63b8cb5cf1784e448ad7be3a930ca6bd");
            return baAccessUtil.<Map<String, Object>>getSiteTreeDetail(id);
        }
        return null;
    }

    /**
     * 奥莱电表
     */
    @RequestMapping(value = "/index")
    public Object index(int type) {
        EesdConfigDTO eesdConfigDTO = eesdIntegrationConfig.getIntegrationConfig(6).get(0);
        if (type == 1) {
            BaAccessUtil baAccessUtil = new BaAccessUtil(eesdConfigDTO.getHost(), eesdConfigDTO.getAppId(), eesdConfigDTO.getToken(),eesdConfigDTO.getLoginProjectId());
            return baAccessUtil.<Map<String, Object>>getSiteTree();
        } else if (type == 2) {
            return baApiHandler.pullDevice(eesdConfigDTO);
        } else if (type == 3) {
            //同步蓝居设备状态
            return lanjuApiHandler.pullEnvDevice(eesdConfigDTO);
        } else if (type == 4) {
            return baApiHandler.pullBaDevice(eesdConfigDTO);
        }
        return null;
    }

    /**
     * 奥莱电表详情
     */
    @RequestMapping(value = "/detail")
    public Object detail(int type,
                         @RequestParam(value = "id", required = false, defaultValue = "d48c04a15da9492f8ef16a65cb5a3cab") String id) {
        EesdConfigDTO eesdConfigDTO = eesdIntegrationConfig.getIntegrationConfig(6).get(0);
        if (type == 1) {
            BaAccessUtil baAccessUtil = new BaAccessUtil(eesdConfigDTO.getHost(), eesdConfigDTO.getAppId(), eesdConfigDTO.getToken());
            return baAccessUtil.<Map<String, Object>>getSiteTreeDetail(id);
        } else if (type == 2) {
            return baApiHandler.pullRecord(eesdConfigDTO);
        }
        return null;
    }

    /**
     * 海康云眸的Token有效期为永久有效，
     * 如果切换环境，需要手动跟新Redis中的Token
     */
    @RequestMapping(value = "/yunmou/updateToken")
    public void  updateToken(Integer projectId){
        PedestrianIntegrationConfigDTO config = haiKangYunMouUtils.getConfig(projectId);
        String ak = config.getAk();
        String sk = config.getSk();
        String token = haiKangYunMouUtils.setToken(projectId,ak,sk);
        log.warn("海康云眸设置的Token为{}",token);
    }


    /**
     * 人行数据补救
     *
     * @param id
     * @param intervalDays 拉取当天差多少天的客流数据，比如拉取昨天，传入-1，适用于 id == 4
     * @param date         传入指定的日期 2022-03-23，拉取这一天的客流数据，适用于 id == 5
     */
    @RequestMapping(value = "/pedestrian", method = RequestMethod.GET)
    public void pedestrian(@RequestParam Integer id, @RequestParam(required = false) Integer intervalDays, @RequestParam(required = false) String date,Integer productId) {
        switch (id) {
            case 1:
                pedestrianDispatcher.executePullPedestrianDevice();
                break;
            case 2:
                pedestrianDispatcher.executePullPedestrianRecordStatistics(null);
                break;
            case 3:
                pedestrianDispatcher.executePullPedestrianDeviceOnlineStatus();
                break;
            case 4:
                pedestrianDispatcher.executePullPedestrianRecordStatistics(intervalDays);
                break;
            case 7:
                pedestrianDispatcher.executePullPedestrianRecord(1, new Date());
                break;
            case 5:
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date parse = simpleDateFormat.parse(date);
                    int i = StatisticsUtil.computeDayDiff(parse, new Date());
                    pedestrianDispatcher.executePullPedestrianRecordStatistics(i);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
            case 6:
                // 测试信息发布
                infoDispatcher.executePullInfoDevice();
                break;
            case 8:
                //刷新配置
                integrationConfig.listenIntegrationConfig(null);
                break;
            case 9://手动同步奥莱主数据
                pedestrianDispatcher.executeSyncStaffAuto();
                break;
            case 10:
                visitorDispatcher.executePullVisitorVrRecord(productId);
                break;
        }
    }

    /**
     * 获取奥莱单个app需要支持的项目名字/域名列表
     * @param projectId
     */
    @RequestMapping(value = "/added-url-list", method = RequestMethod.GET)
    public ResultJson getAddedProjectUrlList(
                         @RequestParam(value = "projectId") int projectId)
    {
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.PROJECT_URL_LIST.getId(), Collections.emptyList());
        PedestrianIntegrationConfigDTO config = integrationConfigDTOList.stream().filter(s->s.getProjectId().equals(projectId)).findAny().orElse(null);
        LinkedList<JSONObject> responseList = new LinkedList<>();
        if(config!=null){
            String orgIndexCode = config.getOrgIndexCode();
            JSONArray arrayObject = JSON.parseArray(orgIndexCode);
            arrayObject.forEach(object-> {
                JSONObject dObject = JSON.parseObject(object.toString());
                String name = dObject.getString("name");
                String url = dObject.getString("url");
                String id = dObject.getString("id");
                HashMap<String, Object> response = new HashMap<>();
                response.put("name", name);
                response.put("url", url);
                response.put("id", id);
                responseList.add(JSONObject.parseObject(JSONObject.toJSONString(response)));
            });
        }
        return ResultJson.success(responseList);
    }

    @RequestMapping(value = "/wether", method = RequestMethod.GET)
    public Object wether(@RequestParam(value = "type", required = false, defaultValue = "1") int type) {
        if (type == 2) {
            EesdConfigDTO eesdConfigDTO = eesdIntegrationConfig.getIntegrationConfig(27).get(0);
            return hwWeatherHandler.weatherTask(eesdConfigDTO);
        }

        String url;
        if (type == 1) {
            url = "http://projwd.apistore.huaweicloud.com/whapi/json/hwcweather/briefcondition";
        } else {
            url = "http://projwd.apistore.huaweicloud.com/whapi/json/hwcweather/aqi";
        }
        CloseableHttpClient client = null;
        try {
            Request request = new Request();
            request.setKey("57d3b1beedd64a56a00070e8dae5351c");
            request.setSecret("c06cc8b41dfb4e71a34d298314f4fe06");
            request.setMethod("GET");
            request.setUrl(url);
            request.addQueryStringParam("lon", "121.35203");
            request.addQueryStringParam("lat", "31.451968");
            HttpRequestBase signedRequest = Client.sign(request);
            client = HttpClients.custom().build();
            HttpResponse response = client.execute(signedRequest);
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(resEntity, "UTF-8"));
                jsonObject.put("key", type == 1 ? "天气实况" : "空气指数");
                return jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 拉取环境数据，包括蓝居环境
     */
    @RequestMapping(value = "/env/pull", method = RequestMethod.GET)
    public void pullLanjuStats(@RequestParam Integer type) {
        switch (type) {
            case 1:
                eesdDispatcher.executeEnvOriginalData();
                break;
            case 2:
                lanJuDispatcher.executeLanjuInfo();
                break;
            case 3:
                eesdDispatcher.executeBESDevice();
                break;
        }
    }

    @GetMapping("/integration-config/index")
    public List getIntegrationConfigs() {
        return IntegrationConfig.integrationConfigList;
    }
    
    
    @GetMapping("/syncGanweiConsumerMsg")
    public void syncGanweiConsumerMsg() {
        romaDeviceDispatcher.syncGanweiConsumerMsg();
    }
    
    
    @GetMapping("/syncRomaDevice")
    public void syncRomaDevice(
    		@RequestParam Integer projectId, 
    		@RequestParam String appId, 
    		@RequestParam String appKey, 
    		@RequestParam String ipAndPort) throws Exception {
    	DeviceProjSupplierCategory config = new DeviceProjSupplierCategory();
    	config.setProjectId(projectId);
    	config.setProductId(21);
    	JSONObject properties = new JSONObject();
    	properties.put("HWAPPID", appId);
    	properties.put("HWAPPKEY", appKey);
    	properties.put("romaIpAndPort", ipAndPort);
    	config.setProperties(properties);
    	ganweiIoTHandler.getRomaDevice(config);
    }
    
    
    @PostMapping("/manualSyncRomaDevice")
    public void saveAndUpdateDevice(@RequestBody String param) throws Exception {
    	JSONObject paramJson = JSONObject.parseObject(param);
    	if(paramJson != null) {
    		List<GanweiRomaDeviceDTO> dtoList = JSONObject.parseArray(paramJson.getString("deviceList") , GanweiRomaDeviceDTO.class);
    		ganweiIoTHandler.saveAndUpdateDevice(paramJson.getInteger("projectId") , paramJson.getInteger("productId"), dtoList);
    	}
    }

}
